package com.test.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.test.cron.QuartzScheduler;
import com.test.dao.*;
import com.test.entities.*;

import com.test.util.HttpUtil;
import com.test.controller.pagination.PaginationFormatting;
import com.test.controller.pagination.PaginationMultiTypeValuesHelper;
import com.test.util.ReportData;
import com.test.util.TraverseFolder;
import com.test.util.Util;
import org.quartz.SchedulerException;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

import static com.test.util.Util.ToDBC;
import static com.test.util.Util.callCmd;

@RestController
@RequestMapping("/api/persons")
public class MainController {

    @Autowired
    private PersonsRepository personsRepository;

    @Autowired
    private FiddlerTemplateRepository fiddlerTemplateRepository;

    @Autowired
    private QuartzScheduler quartzScheduler;

    @Autowired
    private ReportRepository reportRepository;

    @Autowired
    private DictionRepository dictionRepository;

    @Autowired
    private PerformanceTestReportRepository performanceTestReportRepository;

    @Value(("${com.test.paginatio.max-per-page}"))
    Integer maxPerPage;

    String expectedString1 = "\"code\":100";
    String expectedString2 = "成功";
    String expectedString3 = "Error";
    String expectedString4 = "Exception";
    String expectedString5 = "HTTP Status";
    String expectedString6 = "错误";
    String expectedString7 = "异常";
    String expectedString8 = "无";
    String expectedString9 = "308 Permanent Redirect";


//    @RequestMapping(value = "/sex/{result}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
//    public Page<FiddlerTemplate> getSex(@PathVariable String result) {
//
//        Sort sort = new Sort(Direction.ASC, "id");
////        if(result.equals("true")){
////            result = "测试通过";
////        } else {
////            result = "测试不通过";
////        }
//        Pageable pageable = new PageRequest(0, maxPerPage, sort);
//        return fiddlerTemplateRepository.findByFinalTestResult(result,pageable);
//    }

        @RequestMapping(value = "/sex/{result}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public Map<String, PaginationMultiTypeValuesHelper> getSex(@PathVariable String result) {
            //result = result.split("\\|")[0];
            //String pages = result.split("\\|")[1];
            //if (pages == null) {

            //    pages = "1";

            //}

            Sort sort = new Sort(Direction.ASC, "id");

            //Pageable pageable = new PageRequest(Integer.valueOf(pages) - 1, maxPerPage, sort);
            Pageable pageable = new PageRequest(0, maxPerPage, sort);

            PaginationFormatting paginInstance = new PaginationFormatting();

            return paginInstance.filterQuery(result, "", pageable);
    }

//    public ResponseEntity<?> getSexAll() {
//
//        /*
//         * @api {GET} /api/persons/sex Get all sexList
//         * @apiName GetAllSexList
//         * @apiGroup Info Manage
//         * @apiVersion 1.0.0
//         * @apiExample {httpie} Example usage:
//         *
//         *     http /api/persons/sex
//         *
//         * @apiSuccess {String} label
//         * @apiSuccess {String} value
//         */
//
//        ArrayList<Map<String, String>> results = new ArrayList<>();
//
//        for (Object value : personsRepository.findSex()) {
//
//            Map<String, String> sex = new HashMap<>();
//
//            sex.put("label", value.toString());
//
//            sex.put("value", value.toString());
//
//            results.add(sex);
//        }
//
//        ResponseEntity<ArrayList<Map<String, String>>> responseEntity = new ResponseEntity<>(results,
//                HttpStatus.OK);
//
//        return responseEntity;
//    }

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, PaginationMultiTypeValuesHelper> getTestcaseAll(
            @RequestParam(value = "page", required = false) Integer pages
            ,
            @RequestParam(value = "finalTestResult", required = false) String finalTestResult
//            @RequestParam(value = "responseData", required = false) String responseData
    ) {

        /*
         *   @api {GET} /api/persons   Get all or a part of person info
         *   @apiName GetAllInfoList
         *   @apiGroup Info Manage
         *   @apiVersion 1.0.0
         *
         *   @apiExample {httpie} Example usage: (support combinatorial search)
         *
         *       All person：
         *       http /api/persons
         *
         *       You can according to 'sex | email' or 'sex & email'
         *       http /api/persons?sex=xxx&email=xx
         *       http /api/persons?sex=xxx
         *       http /api/persons?email=xx
         *
         *   @apiParam {String} sex
         *   @apiParam {String} email
         *
         *   @apiSuccess {String} create_datetime
         *   @apiSuccess {String} email
         *   @apiSuccess {String} id
         *   @apiSuccess {String} phone
         *   @apiSuccess {String} sex
         *   @apiSuccess {String} username
         *   @apiSuccess {String} zone
         */

        if (pages == null) {

            pages = 1;

        }

        if (finalTestResult == null) {

            finalTestResult = "";

        }

        Sort sort = new Sort(Direction.ASC, "id");

        Pageable pageable = new PageRequest(pages - 1, maxPerPage, sort);

        PaginationFormatting paginInstance = new PaginationFormatting();
        //System.out.println("finalTestResult:"+finalTestResult);
        return paginInstance.filterQuery(finalTestResult, "", pageable);
    }


    @RequestMapping(value = "/testPlan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<FiddlerTemplate> getTestCaseData() {
        return fiddlerTemplateRepository.findAll();
    }

    
    // TODO: 2019/1/9
    @RequestMapping(value = "/findDiction", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Diction getDictionValue(@RequestBody String data) {
        //return dictionRepository.findAll();
        data = data.split("=")[1];
        //System.out.println("data:"+data);
        //List<Diction> fts = JSON.parseObject(data, new TypeReference<ArrayList<Diction>>() {});
        return dictionRepository.findByDictionKey(data);
    }

    // TODO: 2019/1/9
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public boolean getLogin(@RequestBody String data) {
        boolean result = false;
        //data = data.split("=")[1];
        System.out.println("data:"+data);
        if(data.replace("\"","").split("user:")[1].split(",")[0].equals("管理员") && data.replace("\"","").split("user:")[1].split(",")[1].split("pass:")[1].replace("}","").equals("123456"))
            result = true;
        return result;
    }

    @RequestMapping(value = "/diction", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<Diction> getDictionALLValue() {
        Sort sort = new Sort(Direction.ASC, "dictionID");
        return dictionRepository.findAll(sort);
    }

    @RequestMapping(value = "/crawler", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List getCrawler() {
        return TraverseFolder.traverseInfo();
    }

    @RequestMapping(value = "/updateDiction", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public void updateDiction(@RequestBody String data) {
        data = data.substring(8, data.length() - 1);
        //System.out.println("data:"+data);
        ArrayList<Diction> fts = JSON.parseObject(data, new TypeReference<ArrayList<Diction>>() {});
        dictionRepository.deleteAll();
        dictionRepository.save(fts);
    }

    @RequestMapping(value = "/resultData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List getResultData() {
        //return fiddlerTemplateRepository.findAll();
        int successTestCases = 0;
        int failureTestCsases = 0;
        List alist = new ArrayList();
        List<FiddlerTemplate> blist = fiddlerTemplateRepository.findAll();
        for (int i = 0; i < blist.size(); i++) {
            if (blist.get(i).getFinalTestResult().equals("测试通过")) {
                successTestCases++;
            } else {
                failureTestCsases++;
            }
        }
        alist.add(successTestCases);
        alist.add(failureTestCsases);
        return alist;
    }

    @RequestMapping(value = "/genReport", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<FiddlerTemplate> getReportData() {
        List<FiddlerTemplate> alist = fiddlerTemplateRepository.findAll();
        String reportHtml = ReportData.genReport(alist);
        Report report = new Report();
        report.setReport(reportHtml);
        reportRepository.save(report);
        FiddlerTemplate ft = new FiddlerTemplate();
        ft.setResponseData(reportHtml);
        alist.add(ft);
        return alist;
    }




    @RequestMapping(value = "/cron", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Boolean getCronData(@RequestBody String data) {

        return null;
    }

    @RequestMapping(value = "/excel4PerformanceTest2Mail", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<PerformanceTestReport> getExcelDetail4PerformanceTest() {
        //todo delete all files and folders except *.jmx file
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")) {
            callCmd("D:/apache-jmeter-5.0/bin/jmeter.bat -n -t D:/apache-jmeter-5.0/test/ThreadGroup.jmx -l D:/apache-jmeter-5.0/test/test.jtl -e -o D:/apache-jmeter-5.0/test/test/");
            callCmd("D:/apache-jmeter-5.0/bin/JMeterPluginsCMD.bat --generate-csv D:/apache-jmeter-5.0/test/test.csv --input-jtl D:/apache-jmeter-5.0/test/test.jtl  --plugin-type AggregateReport ");
        }
        List<PerformanceTestReport> alist = performanceTestReportRepository.findAll();
        String reportHtml = ReportData.genReport4PerformanceTestReport(alist);
        Report report = new Report();
        report.setReport(reportHtml);
        reportRepository.save(report);

        return null;
    }


    @RequestMapping(value = "/getPerformanceTest", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<PerformanceTestReport> getPerformanceTest() {
        return performanceTestReportRepository.findAll();
    }

    @RequestMapping(value = "/insertDB4PerformanceTest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public PerformanceTestReport updateExcelToDB4PerformanceTest(@RequestBody String data) {
        data = data.substring(8, data.length() - 1);
        ArrayList<PerformanceTestReport> fts = JSON.parseObject(data, new TypeReference<ArrayList<PerformanceTestReport>>() {});
        for (PerformanceTestReport ft2 : fts) {
            performanceTestReportRepository.save(ft2);
        }
        return null;
    }




    @RequestMapping(value = "/excel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<FiddlerTemplate> getExcelDetail(@RequestBody String data) {
        FiddlerTemplate ft = null;
        FiddlerTemplate retestft = null;

        data = data.substring(8, data.length() - 1);
        ArrayList<FiddlerTemplate> fts = JSON.parseObject(data, new TypeReference<ArrayList<FiddlerTemplate>>() {
        });
        List<FiddlerTemplate> newList = new ArrayList<FiddlerTemplate>();
        List<FiddlerTemplate> retestList = new ArrayList<FiddlerTemplate>();
        List retest = new ArrayList();
        String responseData = "";
        //for (FiddlerTemplate ft2 : fts) {
        for(int i = 0 ; i < fts.size() ; i++) {
            ft = fts.get(i);
            //System.out.println(ft.getUrl()+":"+ft.getHead());
            ft.setFullUrl(ft.getProtocol() + "://" + ft.getHost() + ft.getUrl());
            if (ft.getRequestMethod().equals("GET")) {
                responseData = HttpUtil.doGet(ft.getFullUrl(), ft.getContentType(), "");
            } else if (ft.getRequestMethod().equals("POST")) {
                responseData = HttpUtil.doPost(ft.getFullUrl(), ft.getContentType(), "",
                        ft.getHead());
            } else if (ft.getRequestMethod().equals("PUT")) {
                responseData = HttpUtil.doPut(ft.getFullUrl(), ft.getContentType(), "",
                        ft.getHead());
            } else if (ft.getRequestMethod().equals("DELETE")) {
                responseData = HttpUtil.doDelete(ft.getFullUrl(), ft.getContentType(), "",
                        ft.getHead());
            } else {
                System.out.println("TODO http method");
            }
            ft.setResponseData(responseData);
            //System.out.println("responseData:"+responseData);
            if (responseData != null) {
                if (responseData.contains(expectedString1) || responseData.contains(expectedString2)) {
                    ft.setFinalTestResult("测试通过");
                } else if(responseData.contains(expectedString3) || responseData.contains(expectedString4) || responseData.contains(expectedString5)|| responseData.contains(expectedString6 )|| responseData.contains(expectedString7)|| responseData.contains(expectedString8)) {
                    ft.setFinalTestResult("测试不通过");

//                    if(ft.getFullUrl().contains("subCatalogsAndProds.json") && responseData.contains("\"code\":915")){
//                        System.out.println(fts.get(i-1).getResponseData());
//                        //默认/services/wares/v2/catalogs/307/subCatalogsAndProds.json?plateForm=1 接口方法为get
//                        retest = Util.getCatalogId(fts.get(i-1).getResponseData());
//                        String newFullUrl = "";
//                        for(int j = 0 ; j < retest.size() ; j++ ) {
//                            retestft = new FiddlerTemplate();
//                            newFullUrl = Util.changeNumInString(ft.getFullUrl(),retest.get(j).toString());
//                            responseData = HttpUtil.doGet(newFullUrl, retestft.getContentType(), "");
//                            retestft = fts.get(i-1);
//                            retestft.setUrl(newFullUrl.split(ft.getHost())[1]);
//                            retestft.setResponseData(responseData);
//                            retestft.setFullUrl(newFullUrl);
//                            System.out.println(newFullUrl);
//                            retestft.setHost(ft.getHost());
//                            retestft.setHead(ft.getHead());
//                            retestft.setRequestMethod(ft.getRequestMethod());
//                            retestft.setProtocol(ft.getProtocol());
//                            retestft.setContentType(ft.getContentType());
//
//                            retestList.add(retestft);
//                            System.out.println(retestft.getFullUrl());
//                        }
//                    }
                } else {
                    ft.setFinalTestResult("测试通过");
                }
            }
            newList.add(ft);
        }
        if(retestList.size() > 0){
            newList.addAll(retestList);
        }
        return newList;
    }

    @RequestMapping(value = "/insertDB", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public FiddlerTemplate updateExcelToDB(@RequestBody String data) {
        FiddlerTemplate ft = null;
        data = data.substring(8, data.length() - 1);
        ArrayList<FiddlerTemplate> fts = JSON.parseObject(data, new TypeReference<ArrayList<FiddlerTemplate>>() {
        });
        ArrayList<FiddlerTemplate> newList = new ArrayList<FiddlerTemplate>();
        for (FiddlerTemplate ft2 : fts) {
            ft2.setCaseId(String.valueOf(ft2.getId()));
            ft2.setId(0);
            ft2.setFullUrl(ft2.getProtocol() + "://" + ft2.getHost() + ft2.getUrl());
            //System.out.println("ft2.getRequestMethod():"+ft2.getRequestMethod());
            //if (fiddlerTemplateRepository.findByRequestMethodAndFullUrlAndHeadAndResponseData(ft2.getRequestMethod(), ft2.getFullUrl(), ft2.getHead(), ft2.getResponseData()) == null) {
                fiddlerTemplateRepository.save(ft2);
            //}
        }
        return null;
    }

//    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
//    public ResponseEntity<Persons> getUserDetail(@PathVariable Long id) {
//
//        /*
//         *    @api {GET} /api/persons/detail/:id  details info
//         *    @apiName GetPersonDetails
//         *    @apiGroup Info Manage
//         *    @apiVersion 1.0.0
//         *
//         *    @apiExample {httpie} Example usage:
//         *
//         *        http GET http://127.0.0.1:8000/api/persons/detail/1
//         *
//         *    @apiSuccess {String} email
//         *    @apiSuccess {String} id
//         *    @apiSuccess {String} phone
//         *    @apiSuccess {String} sex
//         *    @apiSuccess {String} username
//         *    @apiSuccess {String} zone
//         */
//
//        Persons user = personsRepository.findById(id);
//
//        return new ResponseEntity<>(user, HttpStatus.OK);
//    }

    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<FiddlerTemplate> getUserDetail(@PathVariable Long id) {

        /*
         *    @api {GET} /api/persons/detail/:id  details info
         *    @apiName GetPersonDetails
         *    @apiGroup Info Manage
         *    @apiVersion 1.0.0
         *
         *    @apiExample {httpie} Example usage:
         *
         *        http GET http://127.0.0.1:8000/api/persons/detail/1
         *
         *    @apiSuccess {String} email
         *    @apiSuccess {String} id
         *    @apiSuccess {String} phone
         *    @apiSuccess {String} sex
         *    @apiSuccess {String} username
         *    @apiSuccess {String} zone
         */

        FiddlerTemplate fiddlerTemplate = fiddlerTemplateRepository.findById(id);

        return new ResponseEntity<>(fiddlerTemplate, HttpStatus.OK);
    }

    @RequestMapping(value = "/detail/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    public FiddlerTemplate updateUser(@PathVariable Long id, @RequestBody FiddlerTemplate data) {

        /*
         *  @api {PUT} /api/persons/detail/:id  update person info
         *  @apiName PutPersonDetails
         *  @apiGroup Info Manage
         *  @apiVersion 1.0.0
         *
         *  @apiParam {String} phone
         *  @apiParam {String} zone
         *
         *  @apiSuccess {String} create_datetime
         *  @apiSuccess {String} email
         *  @apiSuccess {String} id
         *  @apiSuccess {String} phone
         *  @apiSuccess {String} sex
         *  @apiSuccess {String} username
         *  @apiSuccess {String} zone

         */
        FiddlerTemplate user = fiddlerTemplateRepository.findById(id);

        //user.setPhone(data.getPhone());
        user.setFinalTestResult(data.getFinalTestResult());

        return fiddlerTemplateRepository.save(user);
    }

//    @RequestMapping(value = "/start", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
//    public void startQuartzJob(@RequestBody String data,HttpServletRequest request) {
//        try {
////            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
////            HttpServletRequest request = servletRequestAttributes.getRequest();
//            String url = "http://"+request.getServerName()+":"+request.getServerPort();
//            quartzScheduler.startJob((data.split("\\:")[1]).replace("\"",""),url);
//        } catch (SchedulerException e) {
//            e.printStackTrace();
//        }
//    }
//
//    @RequestMapping(value = "/info", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
//    public String getQuartzJob() {
//        String info = null;
//        try {
//            info = quartzScheduler.getJobInfo("job1", "group1");
//        } catch (SchedulerException e) {
//            e.printStackTrace();
//        }
//        return info;
//    }
//
//    @RequestMapping(value = "/modify", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
//    public boolean modifyQuartzJob(@RequestBody String data) {
//        boolean flag = true;
//        try {
//            //flag = quartzScheduler.modifyJob(name, group, time);
//            flag = quartzScheduler.modifyJob("job1", "group1", (data.split("\\:")[1]).replace("\"",""));
//        } catch (SchedulerException e) {
//            e.printStackTrace();
//        }
//        return flag;
//    }
//
//    @RequestMapping(value = "/pause")
//    public void pauseQuartzJob(String name, String group) {
//        try {
//            quartzScheduler.pauseJob(name, group);
//        } catch (SchedulerException e) {
//            e.printStackTrace();
//        }
//    }
//
//    @RequestMapping(value = "/pauseAll", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
//    public void pauseAllQuartzJob() {
//        try {
//            quartzScheduler.pauseAllJob();
//        } catch (SchedulerException e) {
//            e.printStackTrace();
//        }
//    }
//
//    @RequestMapping(value = "/resume", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
//    public void resumeQuartzJob() {
//        try {
//            quartzScheduler.resumeJob("job1", "group1");
//        } catch (SchedulerException e) {
//            e.printStackTrace();
//        }
//    }
//
//    @RequestMapping(value = "/delete", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
//    public void deleteJob() {
//        try {
//            //quartzScheduler.deleteJob(name, group);
//            quartzScheduler.deleteJob("job1", "group1");
//        } catch (SchedulerException e) {
//            e.printStackTrace();
//        }
//    }


    @RequestMapping(value = "/start", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public void startQuartzJob(@RequestBody String data,HttpServletRequest request) {
        try {
//            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//            HttpServletRequest request = servletRequestAttributes.getRequest();
            String url = "http://"+request.getServerName()+":"+request.getServerPort();

            JSONObject jsonObject = JSON.parseObject(data);

            quartzScheduler.startJob(ToDBC(jsonObject.getString("data")),jsonObject.getString("jobName"),jsonObject.getString("groupName"),url);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/info", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public String getQuartzJob(@RequestBody String data) {
        String info = null;
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            info = quartzScheduler.getJobInfo(jsonObject.getString("jobName"),jsonObject.getString("groupName"));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return info;
    }

    @RequestMapping(value = "/modify", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public boolean modifyQuartzJob(@RequestBody String data) {
        boolean flag = true;
        try {
            //flag = quartzScheduler.modifyJob(name, group, time);
            JSONObject jsonObject = JSON.parseObject(data);
            flag = quartzScheduler.modifyJob(jsonObject.getString("jobName"),jsonObject.getString("groupName"),ToDBC(jsonObject.getString("data")));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return flag;
    }

    @RequestMapping(value = "/pause", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public void pauseQuartzJob(@RequestBody String data) {
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            quartzScheduler.pauseJob(jsonObject.getString("jobName"),jsonObject.getString("groupName"));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/pauseAll", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public void pauseAllQuartzJob() {
        try {
            quartzScheduler.pauseAllJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/resume", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public void resumeQuartzJob(@RequestBody String data) {
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            quartzScheduler.resumeJob(jsonObject.getString("jobName"),jsonObject.getString("groupName"));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public void deleteJob(@RequestBody String data) {
        try {
            //quartzScheduler.deleteJob(name, group);
            JSONObject jsonObject = JSON.parseObject(data);
            quartzScheduler.deleteJob(jsonObject.getString("jobName"),jsonObject.getString("groupName"));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }




    @RequestMapping(value = "/testJob", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String getJobData() {
        String responseData = "";

        List<FiddlerTemplate> fts = fiddlerTemplateRepository.findAll();
        for (FiddlerTemplate ft : fts) {
            //System.out.println(ft.getUrl()+":"+ft.getHead());
            ft.setFullUrl(ft.getProtocol() + "://" + ft.getHost() + ft.getUrl());
            if (ft.getRequestMethod().equals("GET")) {
                responseData = HttpUtil.doGet(ft.getFullUrl(), ft.getContentType(), "");
            } else if (ft.getRequestMethod().equals("POST")) {
                responseData = HttpUtil.doPost(ft.getFullUrl(), ft.getContentType(), "",
                        ft.getHead());
            } else if (ft.getRequestMethod().equals("PUT")) {
                responseData = HttpUtil.doPut(ft.getFullUrl(), ft.getContentType(), "",
                        ft.getHead());
            } else if (ft.getRequestMethod().equals("DELETE")) {
                responseData = HttpUtil.doDelete(ft.getFullUrl(), ft.getContentType(), "",
                        ft.getHead());
            } else {
                System.out.println("TODO method");
            }
            ft.setResponseData(responseData);
            if (responseData != null) {
                if (responseData.contains(expectedString1) || responseData.contains(expectedString2)) {
                    ft.setFinalTestResult("测试通过");
                } else if (responseData.contains(expectedString3) || responseData.contains(expectedString4) || responseData.contains(expectedString5)|| responseData.contains(expectedString6)|| responseData.contains(expectedString7)|| responseData.contains(expectedString8)|| responseData.contains(expectedString9)) {
                    ft.setFinalTestResult("测试不通过");
                } else {
                    ft.setFinalTestResult("测试通过");
                }
            }
            fiddlerTemplateRepository.save(ft);
        }
        return null;
    }

}